package com.xyzwps.server.paimon.app.aspect

import com.xyzwps.server.paimon.app.dto.ValidInput
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.springframework.stereotype.Component

@Aspect
@Component
class AppServiceAspect {

    companion object {
        private val logger = org.slf4j.LoggerFactory.getLogger(AppServiceAspect::class.java)
    }

    @Around("execution(* com.xyzwps.server.paimon.app.*AppService.*(..))")
    @Throws(Throwable::class)
    fun interceptAppServiceMethods(joinPoint: ProceedingJoinPoint): Any? {
        val methodName = joinPoint.signature.name
        val className = joinPoint.target.javaClass.simpleName
        val args = joinPoint.args
        logger.info("Before executing $className.$methodName with args: ${args.contentToString()}")
        args.forEach { checkArgs(it) }

        try {
            val result = joinPoint.proceed()
            logger.info("After executing $className.$methodName, result: $result")
            return result
        } catch (ex: Exception) {
            logger.error("Exception in $className.$methodName: ${ex.message}", ex)
            throw ex
        }
    }

    private fun checkArgs(a: Any?) {
        if (a == null) {
            return
        }

        when (a) {
            is ValidInput -> a.validateOrThrow()
        }
        // TODO: 优化掉 app filter
    }
}